package com.lw.leetcode.binary.b;

/**
 * Created with IntelliJ IDEA.
 * 1482. 制作 m 束花所需的最少天数
 *
 * @author liw
 * @version 1.0
 * @date 2022/3/17 21:22
 */
public class MinDays {

    public int minDays(int[] bloomDay, int m, int k) {
        if (m > bloomDay.length / k) {
            return -1;
        }
        int st = Integer.MAX_VALUE;
        int end = 0;
        for (int v : bloomDay) {
            st = Math.min(st, v);
            end = Math.max(end, v);
        }
        while (st < end) {
            int mid = (end - st) / 2 + st;
            if (find(bloomDay, mid, m, k)) {
                end = mid;
            } else {
                st = mid + 1;
            }
        }
        return st;
    }

    public boolean find(int[] bloomDay, int days, int m, int k) {
        int bouquets = 0;
        int flowers = 0;
        int length = bloomDay.length;
        for (int i = 0; i < length && bouquets < m; i++) {
            if (bloomDay[i] <= days) {
                flowers++;
                if (flowers == k) {
                    bouquets++;
                    flowers = 0;
                }
            } else {
                flowers = 0;
            }
        }
        return bouquets >= m;
    }


}
